package com.bsb.biz.service;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.bsb.base.common.util.StringUtils;
import com.bsb.base.mapper.SysUserMapper;
import com.bsb.base.mapper.SysUserRoleMapper;
import com.bsb.base.model.SysUser;
import com.bsb.base.model.SysUserExample;
import com.bsb.base.model.SysUserExample.Criteria;
import com.bsb.base.model.SysUserRoleExample;

@Service
public class SysUserService{
	
	@Resource
	private SysUserMapper sysUserMapper;
	
	@Resource
	private SysRoleService sysRoleService;
	
	@Resource
	private PasswordHelper passwordHelper;
	
	@Resource
	private SysUserRoleService sysUserRoleService;
	@Resource
	private SysUserRoleMapper sysUserRoleMapper;
	@Resource
	private SysRoleDeptService sysRoleDeptService;
	@Resource
	private SysOrganizationService sysOrganizationService;
	
	public void addSysUser(SysUser sysUser) {
		sysUserMapper.insertSelective(sysUser);
	}
	
	public void delSysUserById(Long id) {
		sysUserMapper.deleteByPrimaryKey(id);
	}
	
	public void updateSysUser(SysUser sysUser) {
		sysUserMapper.updateByPrimaryKeySelective(sysUser);
	}
	
	public void updateSysUserByExample(SysUser sysUser,SysUserExample sysUserExample){
	    sysUserMapper.updateByExampleSelective(sysUser,sysUserExample);
	}
	
	public SysUser getSysUserById(Long id) {
		return sysUserMapper.selectByPrimaryKey(id);
	}
	
	public List<SysUser> getPageSysUser(SysUserExample sysUserExample) {
		return sysUserMapper.selectPage(sysUserExample);
	}
	
	public int countSysUser(SysUserExample sysUserExample) {
		return sysUserMapper.countByExample(sysUserExample);
	}
	
	public List<SysUser> selectByExample(SysUserExample example){
	    return sysUserMapper.selectByExample(example);
	}
	/**
     * 根据用户名查找用户
     * @param username
     * @return
     */
	public SysUser getUserByUsername(String username){
		SysUserExample sysUserExample = new SysUserExample();
		Criteria criteria = sysUserExample.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<SysUser> users = sysUserMapper.selectByExample(sysUserExample);
		if(users.size()==0){
			return null;
		}
		return users.get(0);
	}
	 /**
     * 根据用户名查找其角色
     * @param username
     * @return
     */
    public Set<String> findRoles(String username) {
    	SysUser user =getUserByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return sysRoleService.findRoles(user.getRole_ids().split(","));
    }

	public Set<String> findPermissions(String username) {
		SysUser user =getUserByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return sysRoleService.findPermissions(user.getRole_ids().split(","));
	}

	public void changePassword(Long id, String newPassword) {
		SysUser user = sysUserMapper.selectByPrimaryKey(id);
		user.setPassword(newPassword);
		passwordHelper.encryptPassword(user);
		sysUserMapper.updateByPrimaryKeySelective(user);
	}
	
	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public  SysUser getUser(){
		Subject subject = SecurityUtils.getSubject();
		String username = (String)subject.getPrincipal();
		if (StringUtils.isNotEmpty(username)){
			SysUser user = getUserByUsername(username);
			if (user != null){
				return user;
			}
			return new SysUser();
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new SysUser();
	}
	/**
	 * 本部门及子部门id
	 * @return
	 */
	public List<Long> getDeptIdsByUser(){
		SysUser user = getUser();
		List<Long> deptIdList = new ArrayList<Long>();
		 //用户角色对应的部门ID列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getId());
		if(roleIdList.size() > 0){
            List<Long> userDeptIdList = sysRoleDeptService.queryDeptIdList(roleIdList.toArray(new Long[roleIdList.size()]));
            deptIdList.addAll(userDeptIdList);
        }

        //用户子部门ID列表
        List<Long> subDeptIdList = sysOrganizationService.getSubDeptIdList(user.getOrganization_id());
        deptIdList.addAll(subDeptIdList);
        
        return deptIdList;
	}

	public List<String> queryAllPerms(long userId) {
		return sysUserMapper.queryAllPerms(userId);
	}

	public List<Long> queryAllMenuId(Long userId) {
		return sysUserMapper.queryAllMenuId(userId);
	}

	public void addUser(SysUser sysUser) {
		sysUserMapper.insertSelective(sysUser);
		String role_ids = sysUser.getRole_ids();
		if(StringUtils.isNotEmpty(role_ids)){
			sysUserRoleService.insertBatchUserRole(sysUser.getId(), Arrays.asList(StringUtils.split(role_ids,",")));
		}
	}

	public void delSysUser(Long id) {
		SysUser record = new SysUser();
		record.setId(id);
		record.setLocked(true);
		sysUserMapper.updateByPrimaryKeySelective(record );
		SysUserRoleExample example = new SysUserRoleExample();
		com.bsb.base.model.SysUserRoleExample.Criteria criteria = example.createCriteria();
		criteria.andUser_idEqualTo(id);
		sysUserRoleMapper.deleteByExample(example );
	}

	public void updateUser(SysUser sysUser) {
		Long id = sysUser.getId();
		String role_ids = sysUser.getRole_ids();
		sysUserMapper.updateByPrimaryKeySelective(sysUser);
		SysUserRoleExample example = new SysUserRoleExample();
		com.bsb.base.model.SysUserRoleExample.Criteria criteria = example.createCriteria();
		criteria.andUser_idEqualTo(id);
		sysUserRoleMapper.deleteByExample(example );
		sysUserRoleService.insertBatchUserRole(id, Arrays.asList(StringUtils.split(role_ids,",")));
	}
	
	
}
